﻿using System;
using System.Diagnostics;
using System.Linq;
using System.Web.Mvc;

namespace Sharp.Portal.Mvc.Filter
{
    /// <inheritdoc />
    /// <summary>
    /// PJAX支持特性
    /// </summary>
    [DebuggerStepThrough]
    public class PjaxSupportAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (!(filterContext.Controller is SharpController pjaxController))
            {
                return;
            }

            var pjax = filterContext.HttpContext.Request.Headers["Pjax"];

            pjaxController.IsPjaxRequest = bool.TryParse(pjax, out var output) && output;

            filterContext.Controller.ViewBag.IsPjaxRequest = output;
        }

        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            var pjaxController = filterContext.Controller as SharpController;

            if (pjaxController == null || !pjaxController.IsPjaxRequest)
            {
                return;
            }

            if (!filterContext.HttpContext.Response.Headers.AllKeys.Any(k => k.Equals("PjaxUrl", StringComparison.CurrentCultureIgnoreCase)))
            {
                var url = filterContext.HttpContext.Request.Url.ToString();

                filterContext.HttpContext.Response.AddHeader("PjaxUrl", url);
            }
        }
    }
}
